package com.disapand.strongarmy.service.impl

import com.disapand.strongarmy.extention.*
import com.disapand.strongarmy.model.*
import com.disapand.strongarmy.service.*
import com.disapand.strongarmy.vo.*
import org.ktorm.database.*
import org.ktorm.dsl.*
import org.ktorm.entity.*
import org.springframework.stereotype.*
import java.time.*

/**
 *
 * @auth disapand
 * @date 2021/10/26 - 16:48 - 星期二
 *
 */
@Service
class PermissionServiceImpl(private val database: Database) : PermissionService {

    /**
     * 新增权限
     *
     * @param label
     * @param permission
     * @return
     */
    override fun add(group: String, label: String, method: String, permission: String): Boolean {
        return database.permissions.add(Permission {
            this.group = group
            this.label = label
            this.method = method
            this.permission = permission
            this.createdAt = LocalDateTime.now()
        }) > 0
    }

    /**
     * 获取权限
     *
     * @param permission
     * @return
     */
    override fun get(permission: String): Permission? {
        return database.permissions.find { it.permission eq permission }
    }

    /**
     * 获取所有权限
     *
     * @return
     */
    override fun get(current: Int, pageSize: Int): PageVO<Permission> {
        return database.permissions.page(current, pageSize)
    }

    /**
     * 获取所有权限
     *
     * @return
     */
    override fun get(): List<Permission> {
        return database.permissions.toList()
    }

    /**
     * 获取所有权限组
     *
     * @return
     */
    override fun getPermissionAllGroup(): MutableList<Map<String, String?>> {
        val result = mutableListOf<Map<String, String?>>()
        val query = database.from(Permissions).selectDistinct(Permissions.group, Permissions.groupLabel)
            .where { Permissions.group notEq "" }
        query.forEach {
            result.add(mapOf("group" to it[Permissions.group], "label" to it[Permissions.groupLabel]))
        }
        return result
    }

    /**
     * 根据权限组获取本组权限的成员
     *
     * @param group
     * @return
     */
    override fun getPermissionByGroup(group: String, current: Int, pageSize: Int): PageVO<Permission> {
        return database.permissions.filter { it.group eq group }.page(current, pageSize)
    }

    /**
     * 新增或更新权限
     *
     * @param label
     * @param permission
     * @return
     */
    override fun addOrUpdate(
        group: String,
        groupLabel: String,
        label: String,
        method: String,
        permission: String
    ): Boolean {
        val get = database.permissions.find { (it.method eq method) and (it.permission eq permission) }
        return if (get != null) {
            get.group = group
            get.groupLabel = groupLabel
            get.label = label
            get.updatedAt = LocalDateTime.now()
            get.flushChanges() > 0
        } else {
            add(group, label, method, permission)
        }
    }
}